<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/13
 * Time: 18:48
 */

namespace App\Http\Controllers\Home;

use App\Model\Address;
use App\Model\Members;
use App\Model\Poundage;
use App\Model\ShopGoods;
use App\Model\ShopGoodsImg;
use App\Model\ShopMemberCart;
use App\Model\ShopOrder;
use App\Model\ShopOrderComment;
use App\Model\StoresCenter;
use App\Model\StoresCenterGoods;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Model\MembersLevel;
use Symfony\Component\HttpKernel\EventListener\ValidateRequestListener;

class OrderController extends BaseController
{
    /**
     * 直商城订单
     * 订单处理
     */
    public function order(Request $request)
    {
        if ($request->ajax()){
            $data = $request->all();
            if(empty($data)){
                return ['code' => 0, 'data' => '数据错误'];
            }
            $user = session('home_user');
            $uid = $user->uid;
            //商品表
            $members = new Members();
            $MembersLevel = new MembersLevel();
            //商品表
            $ShopGoodsModel = new ShopGoods();
            //订单表
            $ShopOrderModel = new ShopOrder();
            //订单详情表
            $ShopOrderCommentModel = new ShopOrderComment();
            $PoundageModel = new Poundage();
            $Poundage = $PoundageModel->first();
            //地址表
            $AddressModel = new Address();
            switch ($data['class']) {
                case 'addSuper':    //超级商城
                    $payTypesChecked = $data['payTypesChecked'];
                    $specs = $data['specs'];
                    $specslength = $data['specslength'];
                    $Checklength = $data['Checklength'];

                    if ( $specslength > 0 && $specs == '' ) {
                        return ['code' => 0, 'data' => '请选择报单产品属性'];
                    }
                    if ( $specslength > 0 ) {
                        if ( $specslength != $Checklength ) {
                            return ['code' => 0, 'data' => '请完整选择报单产品的属性!'];
                        }
                    }

                    $mallData = [];
                    DB::beginTransaction(); //开启事务
                    $goods = $ShopGoodsModel->find_shop( $data['id'] );

                    if ( $data['id'] > 0 ) {
                        if ($specslength > 0){
                            $mallNumData = $goods['goodsname'].'[ '.$specs.' ] X 1';
                        } else {
                            $mallNumData = $goods['goodsname'].' X 1';
                        }
                        $mallData = [
                            0 => [
                                'goods_id' => $data['id'],
                                'num'      => 1
                            ] 
                        ];
                    }
                    $order = [
                        'uid'           => $user->uid,
                        'openid'        => $user->openid,
                        'ordertype'     => 3, //1 优品特选 2 VIP特惠 3 VIP升级
                        'ordersn'       => ORDER_SN(),
                        'price'         => $goods->rulingprice,
                        'originalprice' => $goods->originalprice,
                        'status'        => 0,//-1取消状态，0代付款，1为已付款，2为已发货，3为成功
                        'createtime'    => time(),
                        'mall_goodsid'  => $goods->id,
                        'company_id'    => $user->company_id,
                        'type'          => ($data['type'] == 1)?1:0,
                        'mall_num'      => $mallNumData,
                        'mall_data'     => serialize( $mallData ),
                        'reward_money'  => $goods->rulingprice,
                    ];
                    $order_id = $ShopOrderModel->add_order($order);
                    $ShopOrderCommentModel = new ShopOrderComment();
                    if ($order_id) {
                        $orderComment = [
                            'uid' => $user->uid,
                            'orderid' => $order_id,
                            'openid' => $user->openid,
                            'goodsid' => $data['id'],
                            'price' => $goods->originalprice,
                            'goodsname' => $goods->goodsname,
                            'number' => 1,
                            'specs' => $specs,
                            'createtime' => time(),
                        ];
                        if (!empty($orderComment)) {
                            $rico = $ShopOrderCommentModel->insert($orderComment);
                            if ($rico) {
                                DB::commit();  //提交
                                return ['code' => 1, 'data' => ['id' => $order_id, 'data' => '添加成功']];
                            } else {
                                DB::rollback();  //回滚
                                return ['code' => 0, 'data' => '添加失败'];
                            }
                        }
                    } else {
                        DB::rollback();  //回滚
                        return ['code' => 0, 'data' => '添加失败'];
                    }
                    break;
                case 'add':    //直商城
                    $goods = $ShopGoodsModel->find_shop($data['id']);
                    //查询会员等级
                    $MemberLevel = new MembersLevel();
                    $Redelivery = $data['Redelivery'];
                    if(!$Redelivery){ //是否复投
                        if($user['registered'] == 1){
                            $Level = $MemberLevel->where('conditions','<',floatval($goods->rulingprice))->orderBy('conditions','DESC')->first();
                            if($user['level']){
                                //查询当前等级
                                $userLevel = $MemberLevel->where(['id' => $user['level']])->first();
                                if($userLevel['conditions'] > $Level['conditions']){
                                    return ['code' => 0, 'data' => '请选择更高代理级别的商品'];
                                }
                            }
                        }
                    }


                    $mallData = [];
                    $goodsBuyidOne = StoresCenterGoods::where('goodsname','like','%冷敷贴%')->value('gid');
                    $goodsBuyidTwo = StoresCenterGoods::where('goodsname','like','%百草液%')->value('gid');
                    $mallData = [
                        0 => [
                            'goods_id' => $goodsBuyidOne,
                            //'goods_id' => $goodsBuyidTwo,
                            'num'      => $data['stick']
                        ],
                        1 => [
                            'goods_id' => $goodsBuyidTwo,
                            'num'      => $data['liquid']    
                        ]    
                    ];


                    $order = [
                        'uid'           => $user->uid,
                        'openid'        => $user->openid,
                        'ordertype'     => 1, //1 直商城 2 微商城 3 0元商城
                        'ordersn'       => ORDER_SN(),
                        'price'         => $goods->rulingprice,
                        'originalprice' => $goods->originalprice,
                        'status'        => 0,//-1取消状态，0代付款，1为已付款，2为已发货，3为成功
                        'createtime'    => time(),
                        'mall_goodsid'  => $goods->id,
                        'company_id'    => $user->company_id,
                        'mall_num'      => '冷敷贴：'.$data['stick'].'盒 ，百草液：'.$data['liquid'].'瓶',
                        //'mall_num'      => '百草液：'.$data['stick'].'瓶 ，百草液：'.$data['liquid'].'瓶',
                        'mall_data'     => serialize( $mallData ),
                        'remark'        => empty($Redelivery)?'':'复投',
                        'type'          => empty($Redelivery)?0:1,
                        'reward_money'  => $goods->rulingprice
                    ];
                    $rico = $ShopOrderModel->add_order($order);
                    if ($rico) {
                        return ['code' => 1, 'data' => ['id'=>$rico,'data'=>'添加成功']];
                    } else {
                        return ['code' => 0, 'data' => '设置失败'];
                    }
                    break;
                case 'find':   //查询一条数据
                    if (empty($data['id'])) {
                        return ['code' => 0, 'data' => '参数错误'];
                    }
                    $goods = $ShopOrderModel->find_order( $data['id'] );
                    if ( isset( $data['stores'] ) && !empty( $data['stores'] ) ) {
                        $uid = $goods['uid'];
                    }

                    if (empty($data['address_id'])){
                        $address = $AddressModel->get_address($uid);
                    }else{
                        $address = $AddressModel->get_id_address($data['address_id']);
                    }
                    //$address = $AddressModel->where( [ 'id' => $goods->addressid ] )->first();

                    $member = $members->find_members(['uid' => $uid],['voucher','credit1','credit2','credit3','credit4','credit5','level','stores_number']);
                    if ( empty($member['voucher'])){
                        $member['voucher'] = 0;
                    }
                    if(empty($goods)){
                        return ['code' => 0, 'data' => '没有数据'];
                    }

                    $address == false?$address["address_type"]=0:$address["address_type"]=1;
                    $address["stores_number"] = $member["stores_number"];

                    if ( isset( $address['name'] ) ) 
                    {
                        $goods->receipt_name = $address["name"];
                    }
                    if (  isset( $address['province'] ) && isset( $address['city'] ) && isset( $address['district'] ) && isset( $address['address'] ) ) 
                    {
                        $goods->receipt_adr = $address["province"].$address["city"].$address["district"].$address["address"];
                    }
                    if ( isset( $address['phone'] ) ) {
                        $goods->receipt_phone = $address["phone"];
                    }
                    if($goods->ordertype == 3){
                        // 2 微商城
                        $OrderComment = $ShopOrderCommentModel->get_order_comment($data['id']);
//                        var_dump($data['id']);die;
                        $totalShopNumber = 0; //总商品数量
                        $totalNumber = 0; //商品种类
                        foreach ($OrderComment as $k => $v) {
                            $totalShopNumber += intval($v['number']);
                            $totalNumber += 1;
                            $OrderComment[$k]['totalPrice'] = intval($v['number']) * $v['price'];
                            $goods_img = ShopGoods::where(['id'=>$v['goodsid']])->first();
                            $OrderComment[$k]['img'] = $goods_img['goods_thumb'];
                        }
                        $goods->OrderComment = $OrderComment;
                        $goods->totalShopNumber = $totalShopNumber;
                        $goods->totalNumber = $totalNumber;
                        if (isset($data['stores_number'])){
                            $storeNumber = $data['stores_number'] == '' ? '0' : $data['stores_number'];
                        } else {
                            $storeNumber = $member['stores_number'];
                        }
                        if($data['again'] == 1){
                            //阅读积分
//                            FIGURE_READ($user['credit1'], $user['credit2'],$user['credit4'],$Poundage['deduction'], $money);
                            $moeny = FIGURE_READ($member['credit1'],$member['credit2'],$member['credit4'],$goods_img['read_integral'],$goods['price']);
                            $moeny['type'] = 2;
                        } else {
                            $moeny = FIGURE($member['credit1'],$member['credit2'],$goods['price']);
                            $moeny['type'] = 0;
                        }
//                        if ($member['credit5'] >= 0.5 * ($goods['price'] + $goods['freight'])){
//                            $goods['notice'] = '累计等额复销币即可免单';
//                        }

                    } elseif($goods->ordertype == 2 || 1){
                        // 2 微商城
                        $OrderComment = $ShopOrderCommentModel->get_order_comment($data['id']);
//                        var_dump($data['id']);die;
                        $totalShopNumber = 0; //总商品数量
                        $totalNumber = 0; //商品种类
                        foreach ($OrderComment as $k => $v) {
                            $totalShopNumber += intval($v['number']);
                            $totalNumber += 1;
                            $OrderComment[$k]['totalPrice'] = intval($v['number']) * $v['price'];
                            $goods_img = ShopGoods::where(['id'=>$v['goodsid']])->first();
                            $OrderComment[$k]['img'] = $goods_img['goods_thumb'];
//

                        }
                        $goods->OrderComment = $OrderComment;
                        $goods->totalShopNumber = $totalShopNumber;
                        $goods->totalNumber = $totalNumber;

                        if (isset($data['stores_number'])){
                            $storeNumber = $data['stores_number'] == '' ? '0' : $data['stores_number'];
                        } else {
                            $storeNumber = $member['stores_number'];
                        }
                        if($data['again'] == 1){
                            //复消
//                            $moeny =  FIGURE_READ($member['credit1'], $member['credit2'],$member['credit4'],$Poundage['deduction'], $goods['price']);
                            $moeny = FIGURE_FUXIAO($member['credit1'],$member['credit2'],$member['credit5'],$goods['price']);
                            $moeny['type'] = 2;
                        } else {
                            $moeny = FIGURE($member['credit1'],$member['credit2'],$goods['price']);
                            $moeny['type'] = 0;
                        }
//                        if ($member['credit5'] >= 0.5 * ($goods['price'] + $goods['freight'])){
//                            $goods['notice'] = '累计等额复销币即可免单';
//                        }
                    }elseif($goods->ordertype == 4){
                        $OrderComment = $ShopOrderCommentModel->get_order_comment($data['id']);
                        $totalShopNumber = 0; //总商品数量
                        $totalNumber = 0; //商品种类
                        foreach ($OrderComment as $k => $v) {
                            $totalShopNumber += intval($v['number']);
                            $totalNumber += 1;
                            $OrderComment[$k]['totalPrice'] = intval($v['number']) * $v['price'];
                            $img = ShopGoodsImg::where(['gid'=>$v['goodsid']])->select('img')->first();
                            $OrderComment[$k]['img'] = empty($img->img)?'':$img->img;
                        }
                        $goods->OrderComment = $OrderComment;
                        $goods->totalShopNumber = $totalShopNumber;
                        $goods->totalNumber = $totalNumber;
                        if($data['again'] == 0) {//支付方式
//                            var_dump( $goods['price']);exit;
                            $moeny = FIGUR($member['voucher'], $member['credit1'], $member['credit2'], $member['credit4'], $goods['price']);
                            $moeny['type'] = 0;
                        }
                    }
                    $data = [
                        'order'      => $goods,
                        'address'    => $address,
                        'moeny'      => $moeny,
                    ];
                    if ($goods) {
                        return ['code' => 1, 'data' => $data];
                    } else {
                        return ['code' => 0, 'data' => '数据错误'];
                    }
                    break;
                case 'addorder': //删除
                    break;
                case 'storeNumber': //查出对应门店的编号
                    $storeNumber = StoresCenter::where('shop_name','like','%'.$data["shop_name"].'%')->value("number");
                    if ( $storeNumber ) {
                        return ['code' => 1, 'data' => $storeNumber ];  
                    } else {
                        return ['code' => 0, 'data' => '' ];
                    }
                    break;
            }
        }
    }

    /**
     * 支付页面
     */
    public function orderPage()
    {
        return view('Home.center.orderpage');
    }

    /**
     * 订单详情
     */
    public function orderComment()
    {
        return view('Home.center.ordercomment');
    }
    
}
